package com.mbt.remote.server.mobile;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import com.mbt.bluetooth.manager.BluetoothConnectionManager;
import com.mbt.remote.server.RemoteServer;
import com.mbt.remote.util.Log;

/**
 * The Class MobileImageServer.
 */
public class MobileImageServer implements Runnable {

	/** The robot. */
	private Robot robot = null;

	/** The size. */
	Rectangle size = null;

	/** The os. */
	private OutputStream os = null;

	/**
	 * Instantiates a new mobile image server.
	 * 
	 * @throws AWTException
	 *             the aWT exception
	 */
	public MobileImageServer() throws AWTException {
		this.robot = new Robot();
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		size = new Rectangle(0, 0, 300, 350);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		if (Log.isLogDebugEnabled()) {
			Log.log("Inside Mobile Image Server");
		}
		BluetoothConnectionManager bluetoothConnectionManager = null;
		bluetoothConnectionManager = BluetoothConnectionManager.accept();
		while (!BluetoothConnectionManager.isConnected())
			;
		try {
			while (RemoteServer.isRunning()) {
				if (RemoteServer.isReloadImg()) {
					RemoteServer.setImageSentLock(true);
					BufferedImage image = robot.createScreenCapture(size);
					if (os == null)
						os = bluetoothConnectionManager.getStreamConnection()
								.openOutputStream();
					if (Log.isLogDebugEnabled()) {
						Log.log("MobileImageServer : Sending Image... ");
					}

					ByteArrayOutputStream bos = new ByteArrayOutputStream();

					ImageIO.write(image, "jpeg", bos);

					byte imgData[] = bos.toByteArray();
					System.out.println(imgData.length);
					os.write(imgData.length >> 8);
					os.write(imgData.length & 0xff);
					os.write(imgData);
					os.flush();
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					RemoteServer.setImageSentLock(false);
					if (Log.isLogDebugEnabled()) {
						Log.log("MobileImageServer : Image sent to mobile... ");
					}
					RemoteServer.setReloadImg(false);

				}
			}

		} catch (IOException e) {
			try {
				os.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}

	}

}
